package org.xmx0632.connector.codec;

import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.xmx0632.connector.protocol.JsonMessageParser;
import org.xmx0632.connector.protocol.wrapper.AesWrapper;
import org.xmx0632.connector.protocol.wrapper.Gateway;
import org.xmx0632.connector.util.AesUtil;

import io.netty.channel.ChannelHandler.Sharable;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToMessageDecoder;

/**
 * 解析出data部分数据,按照json格式解码,使用解码后的消息替换原来的消息体内容
 * 
 */
@Component
@Sharable
public class AesMessageDecoder extends MessageToMessageDecoder<String> {

	private static final Logger LOG = LoggerFactory.getLogger(AesMessageDecoder.class);

	@Autowired
	private JsonMessageParser jsonMessageParser;

	@Override
	public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
		LOG.debug("channelReadComplete");
		ctx.flush();
	}

	@Override
	protected void decode(ChannelHandlerContext ctx, String msg, List<Object> out) throws Exception {
		// 按照json格式解析(用字符串提取子串格式解析),提取data数据
		AesWrapper wrapper = jsonMessageParser.parseWrapperData(msg);
		Gateway gateway = wrapper.getGateway();
		String data = wrapper.getData();
		LOG.debug("gateway:{} data:{}", gateway, data);

		if (gateway != null && data != null) {
			String gatewayId = gateway.getGatewayId();
			String accessKey = getAccessKey(gatewayId);
			LOG.debug("gatewayId:{} accessKey:{}", gatewayId, accessKey);
			// 解码data数据为json字符串
			String jsonString = AesUtil.decrypt(accessKey, data);
			LOG.debug("raw data:{}", jsonString);
			out.add(jsonString);

		}

	}

	// TODO 从中科惠软的接口读取对象实例的accessKey属性
	private String getAccessKey(String gatewayId) {
		return null;
	}

	public JsonMessageParser getJsonMessageParser() {
		return jsonMessageParser;
	}

	public void setJsonMessageParser(JsonMessageParser jsonMessageParser) {
		this.jsonMessageParser = jsonMessageParser;
	}

}
